package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApUnlikeBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.UnLikesBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.mongodb.client.result.DeleteResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApUnlikeBehaviorServiceImpl implements ApUnlikeBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    MongoTemplate mongoTemplate;
    //不喜欢 或取消不喜欢
    @Override
    public ResponseResult unlikeBehavior(UnLikesBehaviorDTO dto) {
        //获取当前登录用户
        ApUser user = AppThreadLocalUtils.getUser();
        if(user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"需要登录操作");
        }
        //查询实体行为数据
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        //判断 0 为 不喜欢操作 如果此行为在库中没有数据 就创建
        Query query = Query.query(Criteria.where("entryId").is(apBehaviorEntry.getId()).and("articleId").is(dto.getArticleId()));
        ApUnlikesBehavior one = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
        if(dto.getType().equals(ApUnlikesBehavior.Type.UNLIKE.getCode())){
            if(one == null){
                ApUnlikesBehavior apUnlikesBehavior = new ApUnlikesBehavior();
                apUnlikesBehavior.setEntryId(apBehaviorEntry.getId());
                apUnlikesBehavior.setArticleId(dto.getArticleId());
                apUnlikesBehavior.setType(dto.getType());
                apUnlikesBehavior.setCreatedTime(new Date());
                ApUnlikesBehavior save = mongoTemplate.save(apUnlikesBehavior);
                log.info("不喜欢操作 已创建 返回结果为:{}",save);
            }else {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"已经不喜欢了 不能再点了");
            }
        }// 取消不喜欢 删除对应数据
        else if (dto.getType().equals(ApUnlikesBehavior.Type.CANCEL.getCode())){
            DeleteResult remove = mongoTemplate.remove(query, ApUnlikesBehavior.class);
            log.info("取消不喜欢 操作以执行 返回结果为:{}",remove);
        }
        return ResponseResult.okResult();
    }
}
